package com.qf.p1.controller.base;

import com.qf.p1.model.User;
import com.qf.p1.util.JwtUtil;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * controller的标准定义
 * 集成各种公共方法
 * @author xuzhong
 */
public class BaseController {
    /**
     * 获取当前线程绑定的request的方法
     */
    public HttpServletRequest request(){
        ServletRequestAttributes servletRequestAttributes= (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return servletRequestAttributes.getRequest();
    }

    /**
     * 获取当前线程绑定的response的方法
     */
    public HttpServletResponse response(){
        ServletRequestAttributes servletRequestAttributes= (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return servletRequestAttributes.getResponse();
    }

    /**
     * 获取当前用户携带在请求头中的token
     */
    public String token(){
        return request().getHeader("token");
    }

    /**
     * 获取当前登录用户的实体
     */
    public User user(){
        User user = JwtUtil.checkToken(token());
        return user;
    }

    /**
     * 获取当前登录用户的id
     */
    public Integer userId(){
        User user=user();
        return user==null?null:user.getId();
    }

}
